package com.tian.controller;

import com.tian.OssService;
import com.tian.OssServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * {@code @description:} 文件上传
 *
 * @author tianwc 公众号：Java后端技术全栈
 * 在线刷题 1200+java面试题和1000+篇技术文章：<a href="https://woaijava.cc/">博客地址</a>
 * {@code @date:} 2024/2/21 15:52
 * {@code @version:} 1.0
 */
@Slf4j
@RestController
@RequestMapping("/file")
public class FileController {
    @Resource
    private OssService ossService;

    @RequestMapping("/upload")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam(value = "file", required = false) MultipartFile file) throws IOException {
        log.info("文件上传");
        InputStream is = new ByteArrayInputStream(file.getBytes());
        //文件名
        String trueFileName = file.getOriginalFilename();
        //后缀名
        String suffix = trueFileName.substring(trueFileName.lastIndexOf("."));
        //重新命名
        String fileName = System.currentTimeMillis() + suffix;

        String result = ossService.uploadFile(fileName, is);

        Map<String, Object> res = new HashMap<>();
        if (!result.equals("error")) {
            res.put("success", 1);
            res.put("message", "upload success!");
            res.put("url", result);
        } else {
            res.put("success", 0);
            res.put("message", "upload fail!");
        }
        return res;
    }
}
